//
//  ZDStatus.swift
//  1026SwiftSinaWeiBo
//
//  Created by Apple on 15/10/31.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import SDWebImage

class ZDStatus: NSObject {
    
    //字符串型的微博ID
    var id: Int = 0
    
    //微博创建时间
    var created_at: String?
    
    //微博信息内容
    var text: String? {
    
        didSet {
        
            if let str = text {
            
                attributeText = ZDEmoji.emojiStringToEmojiAttributeString(str, font: UIFont.systemFontOfSize(14))
            }
        }
    }
    
    //微博带表情图片的内容
    var attributeText: NSAttributedString?
    
    //微博来源
    var source: String? {
    
        didSet {
        
            //在didSet方法里面修改属性值 不会再调用属性监视器
            source = source?.linkSource()
        }
    }
    
    /*
        thumbnail_pic  http://ww3.sinaimg.cn/   thumbnail   /89668479jw1exsrmtjuinj209j09kq3d.jpg    //微博配图
    
        bmiddle_pic    http://ww3.sinaimg.cn/   bmiddle     /89668479jw1exsrmtjuinj209j09kq3d.jpg    //中图
    
        original_pic   http://ww3.sinaimg.cn/   large       /89668479jw1exsrmtjuinj209j09kq3d.jpg    //大图
    */
    
    
    //微博配图ID 多图时返回多图ID，用来拼接图片url
    var pic_urls: [[String : AnyObject]]? {
    
        didSet {
            
            let count = pic_urls?.count ?? 0
        
            if count == 0 {
                
                return
            }
            
            storedPictureURLs = [NSURL]()
            
            storedLargePictureURLs = [NSURL]()
            
            for dict in pic_urls! {
                
                if let urlString = dict["thumbnail_pic"] as? String {
                    
                    storedPictureURLs?.append(NSURL(string: urlString)!)
                    
                    //替换字符串
                    let largeUrlString = urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
                    
                    storedLargePictureURLs?.append(NSURL(string: largeUrlString)!)
                }
            }
        }
    }
    
    //保存微博配图URL数组
    private var storedPictureURLs: [NSURL]?
    
    //返回微博配图URL数组
    var pictureURLs: [NSURL]? {
        
        return retweeted_status == nil ? storedPictureURLs : retweeted_status?.storedPictureURLs
    }
    
    
    
    //保存微博配图大图URL数组
    private var storedLargePictureURLs: [NSURL]?
    
    //返回微博配图大图URL数组
    var largePictureURLs: [NSURL]? {
        
        return retweeted_status == nil ? storedLargePictureURLs : retweeted_status?.storedLargePictureURLs
    }

  
    //微博用户
    var user: ZDUser?
    
    
    //微博行高 ———— 缓存cell行高
    var rowHight: CGFloat?
    
    
    //转发微博
    var retweeted_status: ZDStatus?
    
    
    //微博identifier  返回对应cell的identifier
    var identifier: String {
    
        return retweeted_status == nil ? ZDStatusCellReuseIdentifier.normalCell.rawValue : ZDStatusCellReuseIdentifier.forwardCell.rawValue
    }
    
    
    //MARK: - 字典转模型
    init(dict:[String : AnyObject]) {
        
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    
    //忽略模型没有定义的属性
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    
    //MARK: - setValuesForKeys...方法内部会调用该方法
    override func setValue(value: AnyObject?, forKey key: String) {
        
        if key == "user" {
        
            if let dict = value as? [String : AnyObject] {
            
                user = ZDUser(dict: dict)
                
                return
            }
        }
        
        if key == "retweeted_status" {
        
            if let dict = value as? [String : AnyObject] {
            
                retweeted_status = ZDStatus(dict: dict)
                
                return
            }
        }
        
        super.setValue(value, forKey: key)
    }
    
    
    //MARK: - 加载微博模型数组
    class func loadStatuses(since_id: Int, max_id: Int, finished: (list: [ZDStatus]?, error: NSError?) -> Void) {
    
        ZDNetworkTool.sharedInstance.loadStatuses(ZDAccount.loadAccountData()?.access_token, since_id: since_id, max_id: max_id, finished: { (result, error) -> Void in
            
            if error != nil {
            
                print("加载微博数据失败")
                
                finished(list: nil, error: error)
                
                return;
            }
            
            if let statusesArr = result?["statuses"] as? [[String : AnyObject]] {
            
                var statuses = [ZDStatus]()
                
                for dict in statusesArr {
                    //字典转模型 添加到模型数组中
                    statuses.append(ZDStatus(dict: dict))
                }
                
                //加载到微博数据后 开始缓存微博配图
                self.cacheImage(statuses, finished: finished)
                
                return
            }
            
            finished(list: nil, error: nil)
        })
    }
    
    
    //MARK: - 缓存图片
    class func cacheImage(statuses: [ZDStatus]?, finished: (list: [ZDStatus]?, error: NSError?) -> Void) {
    
        //创建组
        let group = dispatch_group_create()
        
        //如果模型数组为空 直接返回
        guard let cacheStatus = statuses else {
        
            return
        }
        
        //记录下载图片的总大小
        var length = 0
        
        //遍历模型数组
        for status in cacheStatus {
        
            //如果模型的配图URL数组为空，就继续遍历下一个
            if status.pictureURLs == nil {
            
                continue
            }
            
            //为了节省流量 和 提高性能 只缓存有一张配图的微博
            if status.pictureURLs!.count == 1 {
                
                let url = status.pictureURLs![0]
            
//                SDWebImageManager.sharedManager().downloadWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, error, _, _) -> Void in
//                    
//                    
//                })
                
                //进入组
                dispatch_group_enter(group)
                
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, error, _, _, _) -> Void in
                    
                    //离开组
                    dispatch_group_leave(group)
                    
                    if error != nil {
                    
                        print("下载图片失败\(url)")
                        
                        return
                    }
                    
//                    print("下载图片成功\(url)")
                    
                    //图片转成二进制
                    if let data = UIImagePNGRepresentation(image) {
                    
                        //拼接
                        length += data.length
                    }
                })
            }
        }
        
        //图片缓存完毕  通知调用者
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            
            print("所有图片缓存完成：\(length) Byte")
            
            finished(list: statuses, error: nil)
        }
    }
    
    
    override var description: String {
    
        let array = ["created_at", "text", "source", "pic_urls", "user", "retweeted_status"]
        
        return "\n\t微博模型：\(dictionaryWithValuesForKeys(array))"
    }

}
